package org.rich.charlesmurphy.core.parser;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;

import org.rich.charlesmurphy.core.Descriptor;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.Ostermiller.util.CSVPrinter;

/**
 * Class for writing out data in memory to disk, in CSV format.
 * @author Rich O'Connell
 */
public class CsvWriter<T> {


	public void write(File csv, Descriptor descriptor, List<T> data) {

		Writer writer = null;
		try {
			try {

				writer = new BufferedWriter(new FileWriter(csv));
				CSVPrinter printer = new CSVPrinter(writer);
				printer.setAlwaysQuote(true);
				BeanWrapper bw;
				for (T o : data) {
					bw = new BeanWrapperImpl(o);
					for (int i = 0; i < descriptor.size(); i++) {
						printer.print((String)bw.getPropertyValue(descriptor.getFieldName(i)));
					}
					printer.println();
				}
			}
			finally {
				if (writer != null) {
					writer.close();
				}
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}


}
